// pages/car/takecar/addpeople/index.ts
import { Car } from '../../../../api/car'
import {savePeople,TakePeople,list,doDelete} from '../../../../api/take_car'
import { LENGYU_SUCCESS_CODE } from '../../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    car:{
      id:""
    },
    showTakeButton:false,
    takeCarPeopleList:[
    ],
    dialogShow: false,
    deleteDialogShow: false,
    toDeleteTakeId:"",
    buttons: [{ text: '取消' }, { text: '确定' }], 
    error:"",
    formData: {
    },
    rules: [
      {
          name: 'playHours',
          rules: {required: false, message: '你不写打多久吗？'},
      },
      {
        name: 'gs',
        rules: {required: true, message: '你还没有填装等'},
      },
      {
        name: 'career',
        rules: {required: true, message: '你还没选职业'},
      },
      {
        name: 'position',
        rules: {required: true, message: '你还没选天赋'},
      },
      {
        name: 'need',
        rules: {required: true, message: '你不需要车主付出吗？'},
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
      // 建立数据通道
      const eventChannel = this.getOpenerEventChannel()
      // 监听'delivery'事件，并获取数据包
      let that = this
      eventChannel.on('deliveryParam', data => {
        that.setData({
          'car':data.car

        })
        this.getTakePeople()
      })
 
      this.setData({
        'showTakeButton':wx.getStorageSync('carListType')=="takeCar"
      })
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  showDialog(){
    this.setData({
      dialogShow: true,
      formData:{}
     })
  },
  async tapDeleteDialogButton(e:any){
    if(e.detail.index==0){
      this.closeDialog()
    }
    else if(e.detail.index==1){
      let result = await doDelete(this.data.toDeleteTakeId);
      if(result.code==LENGYU_SUCCESS_CODE){
        this.getTakePeople();
        this.closeDialog()
      }
    }
  },
  tapDialogButton(e:any) {
    console.log(e);
    if(e.detail.index==0){
      console.log("点击取消按钮")
      this.closeDialog()
    }
    else if(e.detail.index==1){
      console.log("点击确认按钮")
      this.submitForm();
    }
  },
  closeDialog(){
      this.setData({
          dialogShow: false,
          deleteDialogShow:false,
          formData:{},
          toDeleteTakeId:"",
      })
  },
  bindCareerChange(e:any){
    console.log("自定义组件事件",e)
    this.setData({
      'formData.career':e.detail.value[0],
      'formData.position':e.detail.value[1],
    })
  },
  // bindPositionChange(e:any){
  //   this.setData({
  //     'formData.position':this.data.positionOptions[e.detail.value].text
  //   })
  // },
  bingPlayHoursChange(e:any){
    this.setData({
      'formData.playHours':e.detail.value
    })
  },
  bingGsChange(e:any){
    this.setData({
      'formData.gs':e.detail.value
    })
  },
  bingNeedChange(e:any){
    this.setData({
      'formData.need':e.detail.value
    })
  },
  async getTakePeople(){
    let param={
      car_id:this.data.car.id
    }
    let selfOpenId = wx.getStorageSync("openId")
    let selfUserId = wx.getStorageSync("userId")
    let result = await list(param);
    if(result.code==LENGYU_SUCCESS_CODE){
      if(result.data){
        this.setData({
          'takeCarPeopleList':result.data
        })
      }
      this.data.takeCarPeopleList.forEach((item:TakePeople,index)=>{
        let key:string =  "takeCarPeopleList["+index+"].self";
         if(item.userId==selfUserId){
          this.setData({
            [key]:true
          })
         }
         else{
          this.setData({
            [key]:false
          })
         }
      })
      console.log(this.data.takeCarPeopleList)
    }
  },
  editTakePeople(e:any){
    this.setData({
      dialogShow: true,
      formData:e.currentTarget.dataset.people
    })
  },
  async deleteTakePeople(e:any){
    //takeId
    this.setData({
      deleteDialogShow: true,
      toDeleteTakeId:e.currentTarget.dataset.takeid
    })
  
  },
  async submitForm(){
    this.selectComponent('#form').validate( async (valid:any, errors:any) =>{
        console.log('valid', valid, errors)
        if (!valid) {
            const firstError = Object.keys(errors)
            if (firstError.length) {
                this.setData({
                    error: errors[firstError[0]].message
                })
            }
        } else {
          this.setData({
            'formData.carId':this.data.car.id
          })
          let result = await savePeople(this.data.formData as TakePeople);
          if(result.code==LENGYU_SUCCESS_CODE){
            this.closeDialog();
            this.getTakePeople();
          }
  
        }
    })
    }
})